// 导入数据库操作模块
const db = require('../db/index')
const dayjs = require('dayjs')

exports.addMessage = (req, res) => {
    // 获取客户端提交到服务器的信息
    const userinfo = req.body

    // 定义插入新留言的SQL语句
    const sqlStr = 'insert into ev_message set ?'
    db.query(sqlStr, { username: userinfo.username, content: userinfo.content, message_date: userinfo.messageDate }, (err, results) => {
        if (err) return res.cc(err)

        // 定义留言日期数量+1的SQL语句
        const sql = 'update ev_message_number set count=count+1 where date = ?'
        db.query(sql, userinfo.messageDate, (err, results) => {
            if (err) return res.cc(err)
            res.send({
                status: 0,
                message: '留言成功',
            })
        })
    })
}

exports.getMessage = (req, res) => {
    // 获取客户端提交到服务器的信息
    const userinfo = req.body

    // 定义 SQL 语句，查询ev_message数据表总数
    const sqlStr = 'select count(*) as total from ev_message'
    db.query(sqlStr, (err, results) => {
        // 执行SQL语句失败
        if (err) return res.cc(err)
        // 执行SQL语句成功
        const total = JSON.parse(JSON.stringify(results))[0].total
        const current = (userinfo.current - 1) * userinfo.size
        const size = userinfo.size
        const sql = 'select * from ev_message order by id limit ' + current + ',' + size
        db.query(sql, (err, results) => {
            // 执行SQL语句失败
            if (err) return res.cc(err)
            // 执行SQL语句成功
            results.forEach(item => {
                item.message_date = dayjs(item.message_date).add(0, 'day').format('YYYY-MM-DD');
            });
            res.send({
                status: 0,
                message: '',
                data: {
                    messageData: results,
                    total: total
                }
            })
        })

    })
}